<template>
  <div id="Login">
    <div class="login_block">
      <div class="logo">
        <img src="../../assets/image/login_logo.png" alt="">
      </div>
      <el-form :model="formData" status-icon :rules="rules" ref="loginForm">
        <el-form-item prop="name">
          <el-input
            type="text"
            v-model="formData.name"
            auto-complete="off"
            placeholder="请输入账号"
            @keyup.enter.native="$refs.password.focus()"
            :disabled="loading"
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            ref="password"
            type="password"
            v-model="formData.password"
            auto-complete="off"
            placeholder="请输入密码"
            @keyup.enter.native="loginBtnClick('loginForm')"
            :disabled="loading">
          </el-input>
        </el-form-item>
        <el-form-item  prop="captcha" v-if="needCaptcha">
          <span style="display: flex; justify-content: flex-end;">
            <el-input
              style="width: calc(100% - 120px)"
              type="text"
              v-model="formData.captcha"
              placeholder="验证码"
              :disabled="loading"
              @keyup.enter.native="loginBtnClick('loginForm')">
            </el-input>
            <div class="captcha_block" v-loading="captchaLoading" @click="loadCaptcha">
              <img :src="captchaBase64" alt="" width="120px" height="40px">
            </div>
          </span>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="loginBtnClick('loginForm')"
            :loading="loading"
          >
            {{loginBtnTxt}}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import API from '@/config/api.js'
import ErrorConfig from '@/config/error.config.js'
import uuidv1 from 'uuid/v1'
export default {
  name: 'Login',
  data () {
    return {
      formData: {
        name: '',
        password: '',
        captcha: '',
        captchaUuid: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        captcha: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      },
      loading: false,
      loginBtnTxt: '登 录',
      needCaptcha: false,
      captchaBase64: '',
      captchaLoading: false
    }
  },
  methods: {
    async toLogin () { // 处理登录
      this.loading = true
      this.loginBtnTxt = '登 录 中...'
      const response = await API.login(this.formData)
      const {accessToken, refreshToken} = response.data // 登录
      const { code } = response
      if (code === 1) {
        this.loginBtnTxt = '加 载 数 据 中...'
        // 存储token数据
        window.sessionStorage.setItem('accessToken', accessToken)
        window.sessionStorage.setItem('refreshToken', refreshToken)
        const res = await API.getUserInfo() // 查询用户资料
        this.loading = false
        this.loginBtnTxt = '登 录'
        if (res.code === 1) {
          window.sessionStorage.setItem('userInfo', JSON.stringify(res.data))
          this.$message({
            message: '登录成功',
            type: 'success'
          })
          this.$router.push({ path: '/index' }) // 跳转首页
          if (this.needCaptcha) {
            this.needCaptcha = false
          }
        } else {
          this.$message.error(ErrorConfig[res.code])
        }
      } else {
        this.loading = false
        this.loginBtnTxt = '登 录'
        if (code === 20205 || code === 20206) { // 需要验证码来登录
          if (!this.needCaptcha) {
            this.$message({
              type: 'warning',
              message: '请输入验证码！'
            })
            this.needCaptcha = true
            this.loadCaptcha()
            return false
          }
          this.loadCaptcha()
        }
        this.loadCaptcha()
        if (code === -1) {
          const { msg } = response
          this.$message.error(msg)
        } else {
          this.$message.error(ErrorConfig[code])
        }
      }
    },
    loginBtnClick (formName) { // 登录按钮点击
      let _self = this
      this.$refs[formName].validate((valid) => {
        if (valid) { // 表单验证通过
          _self.toLogin()
        } else {
          return false
        }
      })
    },
    async loadCaptcha () { // 加载验证码
      const s = uuidv1()
      this.formData.captchaUuid = s
      const response = await API.getCaptch({ s })
      const reader = new FileReader()
      reader.readAsDataURL(response)
      reader.onload = (e) => {
        this.captchaBase64 = e.target.result
        console.log(e.target.result)
      }
    }
  }
}
</script>

<style scoped lang="scss">
  #Login {
    position: relative;
    width: 100vw;
    height: 100vh;
    background: url("../../assets/image/login_bg.jpeg") no-repeat;
    background-position: center center;
    .login_block {
      position: absolute;
      top: 44%; left: 50%;
      transform: translate(-50%, -50%);
      width: 400px;
      .logo {
        text-align: center;
      }
      .el-form {
        box-sizing: border-box;
        padding: 30px 20px 1px 20px;
        margin-top: 20px;
        border-radius: 4px;
        background: #fff;
        .el-form-item {
          .el-button {
            width: 100%;
          }
          .captcha_block {
            box-sizing: border-box;
            width: 120px;
            height: 40px;
            cursor: pointer;
            background: #eee;
          }
        }
      }
    }
  }
</style>
